<template>
  <view>
    <ve-form-item :required="siteRequired" :prop="config.siteId" :label="config.siteLabel" class="form-item-site">
      <remote-select v-model="form[config.siteId]" :label="form[config.siteName]" v-bind="remoteSelectConfig" @change="changeSiteIdFn" />
    </ve-form-item>
    <ve-form-item :label="config.serviceFlagLabel" class="form-item-type">
      <ve-radio v-model="form[config.serviceFlag]" :disabled="serviceFlagDisabled" :list="radioList" />
      <template #footer v-if="form[config.serviceFlag] == 1">
        <view class="choice-address-wrapper">
          <view class="location-address">
            <ve-input
              type="textarea"
              v-model="form[config.address]"
              :autoHeight="true"
              :cursorSpacing="10"
              :placeholder="config.addressPlaceholder"
              placeholderStyle="color: #9ea5bbff"
              @input="onTextareaInput"
              @clear="onTextareaClear"
            />
          </view>
          <view class="location-point" @tap="pointMapTapFn">
            <ve-icon name="location" width="28" height="28" />
            <text>地图选点</text>
          </view>
        </view>
        <view class="coordinate-tips" v-if="showCoordinateTips"> 当前位置无法定位，将会影响费用计算，可前往地图选址 </view>
      </template>
    </ve-form-item>
  </view>
</template>
<script setup>
  import { ref, inject, computed, nextTick, onMounted } from 'vue'
  import { getSiteLeaseListAPI, getSiteLeaseDetailAPI } from '@/api/order/sOrder'
  const props = defineProps({
    type: String, //  site | returnSite
    mode: {
      type: String,
      default: '',
    },
    // 门店是否必选
    siteRequired: {
      type: Boolean,
      default: false,
    },
  })
  const config = computed(() => {
    return props.type == 'site'
      ? {
          siteLabel: '取车门店',
          siteId: 'siteId',
          siteName: 'siteName',
          serviceFlag: 'sendServiceFlag',
          serviceFlagLabel: '取车类型',
          address: 'address',
          addressPlaceholder: '请输入上门送车地址',
          longitude: 'longitude',
          latitude: 'latitude',
        }
      : {
          siteLabel: '还车门店',
          siteId: 'returnSiteId',
          siteName: 'returnSiteName',
          serviceFlag: 'returnServiceFlag',
          serviceFlagLabel: '还车类型',
          address: 'returnAddress',
          addressPlaceholder: '请输入上门取车地址',
          longitude: 'returnLongitude',
          latitude: 'returnLatitude',
        }
  })
  // 显示无坐标提示语
  const showCoordinateTips = computed(() => {
    const address = form.value[config.value.address]
    const longitude = form.value[config.value.longitude]
    const latitude = form.value[config.value.latitude]
    if (address) {
      return !longitude && !latitude
    } else {
      return false
    }
  })
  // 输入框输入
  const onTextareaInput = () => {
    form.value[config.value.longitude] = undefined
    form.value[config.value.latitude] = undefined
  }
  // 清空
  const onTextareaClear = () => {
    form.value[config.value.longitude] = undefined
    form.value[config.value.latitude] = undefined
  }
  const remoteSelectConfig = computed(() => {
    return props.type == 'site'
      ? {
          type: 'site_listBystaff',
          params: { siteStatusList: [10], oldId: form.value.siteId },
        }
      : {
          type: 'site_lease_list',
          // siteId 对应取车门店
          params: { siteStatusList: [10], siteType: 40, siteId: form.value.siteId, oldId: form.value.returnSiteId },
        }
  })
  const radioList = computed(() => {
    return props.type == 'site'
      ? [
          { label: '到店取车', value: 0 },
          { label: '上门送车', value: 1 },
        ]
      : [
          { label: '到店还车', value: 0 },
          { label: '上门取车', value: 1 },
        ]
  })
  const orderInfo = props.mode == 'edit' && props.type == 'site' ? inject('orderInfo') : {}
  const form = inject('form')
  // 门店短租配置
  const siteConfig = ref({})
  // 上门送取车开关是否打开
  const serviceFlagDisabled = computed(() => {
    return !siteConfig.value.isOnsiteService
  })
  // 切换门店
  const prevSiteId = ref()
  const prevSiteName = ref()
  const changeSiteIdFn = (val, option, isEditInit = false) => {
    let type = props.type
    new Promise((resolve) => {
      if (props.mode == 'edit' && type == 'site' && !isEditInit) {
        // 编辑订单，修改取车门店
        uni.showModal({
          title: '确认',
          content: '变更取车门店，系统将重置车型和车牌号，请确认是否修改？',
          confirmColor: '#27BA9B',
          success(res) {
            if (res.confirm) {
              prevSiteId.value = val
              prevSiteName.value = option.siteName
              resolve()
            } else {
              if (prevSiteId.value) {
                form.value.siteId = prevSiteId.value
                form.value.siteName = prevSiteName.value
              } else {
                form.value.siteId = orderInfo.value.siteId
                form.value.siteName = orderInfo.value.siteName
              }
            }
          },
        })
      } else {
        resolve()
      }
    }).then(() => {
      form.value[config.value.siteName] = option.siteName
      // 切换取车门店，需要清空车型和车牌
      if (type == 'site') {
        // 清空排车信息
        form.value.carId = undefined
        form.value.carLicenseNo = undefined
        // 排车车型
        form.value.carModelId = undefined
        form.value.carModelName = undefined

        // 清空预订车型信息
        form.value.originalModelId = undefined
        form.value.originalModelName = undefined

        // 更改完取车门店，需要判断当前选择的还车门店是否为可选择的还车门店
        // 因为取车门店，可能选择了上门取送车，还车门店也需要支持上门取送车
        // 并且需要判断是否支持跨城取送车
        if (form.value.returnSiteId) {
          const param = {
            siteType: 40,
            siteStatusList: [10],
            siteId: form.value.siteId,
          }
          getSiteLeaseListAPI(param).then((res) => {
            // 还车门店列表获取
            const list = res.result
            if (list.length > 0) {
              if (!list.find((site) => site.id == form.value.returnSiteId)) {
                uni.$emit('clearReturnSite')
              }
            } else {
              uni.$emit('clearReturnSite')
            }
          })
        }
      }
      // 读取门店配置
      // 获取门店租赁配置详情
      getSiteLeaseDetailAPI({ id: val }).then(({ result }) => {
        siteConfig.value = result.shortSiteConfig || {}
        // 通过 nextTick 获取 最新的 上门送取车开关是否可选
        nextTick(() => {
          if (serviceFlagDisabled.value) {
            // 如果当前是选中的，需要取消选中
            if (form.value[config.value.serviceFlag] == 1) {
              form.value[config.value.serviceFlag] = 0
              form.value[config.value.address] = undefined
              form.value[config.value.longitude] = undefined
              form.value[config.value.latitude] = undefined
            }
          }
        })
      })
    })
  }
  // 点击地图选址
  const pointMapTapFn = () => {
    if (form.value[config.value.serviceFlag]) {
      let longitude = form.value[config.value.longitude]
      let latitude = form.value[config.value.latitude]
      uni.setStorageSync('showMapLnglatOperateType', props.type)
      if (longitude && latitude) {
        uni.setStorageSync('showMapLnglat', [longitude, latitude])
      } else {
        uni.removeStorageSync('showMapLnglat', [longitude, latitude])
      }
      uni.navigateTo({ url: '/pages/map/showMap' })
    }
  }

  onMounted(() => {
    if (props.type == 'returnSite') {
      uni.$on('clearReturnSite', () => {
        form.value.returnSiteId = undefined
        form.value.returnSiteName = undefined
        form.value.returnServiceFlag = 0
        form.value.returnAddress = undefined
        form.value.returnLongitude = undefined
        form.value.returnLatitude = undefined

        siteConfig.value = {}
      })
    }
  })

  defineExpose({
    changeSiteIdFn,
  })
</script>
<style lang="less" scoped>
  .rent-days {
    position: absolute;
    right: 0;
    top: 33rpx;
    color: #3072f6;
  }
  .separate-range-picker {
    width: 100%;
    /deep/ .time-choose {
      width: 100%;
    }
  }
  .map-location {
    color: rgb(var(--primary-6));
    font-size: 14px;
    cursor: pointer;
    svg {
      color: rgb(var(--primary-6));
    }
  }
  .map-location.disabled {
    cursor: no-drop;
    color: rgba(24, 144, 255, 0.5);
    svg {
      color: rgba(24, 144, 255, 0.5);
    }
  }
  .choice-address-wrapper {
    width: 100%;
    min-height: 50px;
    background: #f7f8fa;
    position: relative;
    padding: 12rpx 190rpx 12rpx 0rpx;
  }
  .coordinate-tips {
    color: #f75b5b;
    margin-top: 16rpx;
  }
  .location-address {
    width: 100%;
    /deep/ uni-textarea {
      width: 100%;
    }
  }
  .location-point {
    height: 40rpx;
    display: flex;
    align-items: center;
    width: 160rpx;
    flex-shrink: 0;
    position: absolute;
    right: 24rpx;
    top: 36rpx;
    text {
      margin-left: 16rpx;
      font-size: 28rpx;
      color: #1890ff;
    }
  }
</style>
